﻿using Exceptionless;
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Helpers;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Builder;
using Serilog.AspNetCore;
using Microsoft.Extensions.DependencyInjection;

public static class SerilogHelperExtensions
{
    /// <summary>
    /// 初始化serilog,并注册Serilog.ILogger
    /// </summary>
    public static IServiceCollection AddSerilogHelper(this IServiceCollection services, IConfiguration configuration, Action<SerilogHelperOptions> configureOptions = default, Action<LoggerConfiguration> configureLogger = default)
    {
        SerilogFactory.Init(configuration, configureOptions, configureLogger);

        //注册ILogger
        services.AddSingleton<ILogger>(x => Log.Logger);

        return services;
    }

    /// <summary>
    /// 使用serilog记录请求中间件
    /// </summary>
    public static IApplicationBuilder UseSerilogRequestLoggingz(this IApplicationBuilder app, Action<RequestLoggingOptions> configureOptions = null)
    {
        app.UseSerilogRequestLogging(options =>
        {
            options.MessageTemplate = "Request {RequestProtocol} {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.00}ms";
            options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
            {
                diagnosticContext.Set("RequestId", httpContext.TraceIdentifier);
                diagnosticContext.Set("RequestProtocol", httpContext.Request.Protocol);
            };
            configureOptions?.Invoke(options);
        });
        return app;
    }
}
